package ex01.pyrmont;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

import ex02.pyrmont.ServletProcessor;
import ex02.pyrmont.StaticResourceProcessor;

public class HttpServer {
	
	public static final String WEB_ROOT = System.getProperty("user.dir") + File.separator + "webroot";
	public static final String SERVLET_PACKAGE = "ex02.pyrmont.servlet.";
	private static final String SHUTDOWN_COMMAND = "/SHUTDOWN";
	private boolean shutdown = false;
	
	public static void main(String[] args) {
		
		HttpServer server = new HttpServer();
		server.await();
	}
	
	public void await() {
		
		ServerSocket serverSocket = null;
		int port = 8080;
		try {
			serverSocket = new ServerSocket(port, 1, InetAddress.getByName("127.0.0.1"));
		} catch (UnknownHostException e) {
			e.printStackTrace();
			System.exit(1);
		} catch (IOException e) {
			e.printStackTrace();
			System.exit(1);
		}
		
		while (!shutdown) {
			
			Socket socket = null;
			InputStream inputStream = null;
			OutputStream outputStream = null;
				try {
					System.out.println("WEB_ROOT: "+HttpServer.WEB_ROOT);
					socket = serverSocket.accept();
					inputStream = socket.getInputStream();
					outputStream = socket.getOutputStream();
					Request request = new Request(inputStream);
					request.parse();// 解析请求,并给uri赋值
					System.out.println("uri: "+request.getUri());
					Response response = new Response(outputStream);
					response.setRequest(request);
					// 根据uri处理servlet请求
					if (request.getUri().startsWith("/servlet/")) {
						// 处理servlet 请求
						ServletProcessor processor = new ServletProcessor();
						processor.process(request, response);
					} else {// 处理静态文件请求
						StaticResourceProcessor processor = new StaticResourceProcessor();
						processor.process(request, response);
					}
					
					socket.close();
					shutdown = request.getUri().equals(SHUTDOWN_COMMAND);
				} catch (IOException e) {
					e.printStackTrace();
					continue;
				}
		}
	}
}
